The classic Fibonacci generator example

First, a plain function to generate the Nth number in the Fibonacci series:


In [1]:
def fibonacci(n):
    a, b = 0, 1
    while n:
        a, b = b, a + b
        n -= 1
    return a

In [2]:
for n in range(10):
    print(fibonacci(n))


0
1
1
2
3
5
8
13
21
34

In [3]:
[fibonacci(n) for n in range(10)]


Out[3]:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

The generator

Now, a generator function


In [4]:
def gen_fibo(n):
    a, b = 0, 1
    while n:
        yield a
        a, b = b, a + b
        n -= 1

In [13]:
g10 = gen_fibo(10)
g10


Out[13]:
<generator object gen_fibo at 0x7fb294710410>

In [14]:
f10 = list(g10)
f10


Out[14]:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

In [15]:
for n in gen_fibo(n):
    print(n)


0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765

Fibonacci numbers and the golden ratio


In [7]:
f10 = list(gen_fibo(10))
ratios = [a/b for a, b in zip(f10[2:], f10[1:-1])]
ratios


Out[7]:
[1.0,
 2.0,
 1.5,
 1.6666666666666667,
 1.6,
 1.625,
 1.6153846153846154,
 1.619047619047619]

In [8]:
φ = (1 + 5**0.5) / 2
φ


Out[8]:
1.618033988749895

In [10]:
%matplotlib inline

import matplotlib.pyplot as plt

plt.figure()
plt.plot(ratios)
plt.axhline(φ, color='r')


Out[10]:
<matplotlib.lines.Line2D at 0x7fb297115438>